package com.spring.quickstart.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.spring.quickstart.entity.User;
import com.spring.quickstart.service.IUserService;

@Controller
public class UserController {

	private IUserService userService;

	public IUserService getUserService() {
		return userService;
	}

	@Autowired
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	//http://127.0.0.1:8080/userController/1/showUser.do
	@RequestMapping("/{id}/showUser")
	public String showUser(@PathVariable String id, ModelMap modelMap, HttpServletRequest request) {
		User u = userService.getUserEntityById(id);

		if (u == null) {
			u = new User();
			u.setEmail("");
			u.setUserId("");
		}
		modelMap.put("user", u);
		return "showUser";
	}

	//http://127.0.0.1:8080/userController/showUser.do?id=1
	@RequestMapping({ "showUser", "showUser.htm?id=1" })
	public String showUserEntity(String id, ModelMap modelMap, HttpServletRequest request) {
		User u = userService.getUserEntityById(id);
		if (u == null) {
			u = new User();
			u.setEmail("");
			u.setUserId("");
		}
		modelMap.put("user", u);
		return "user/showUser";
	}

	@RequestMapping("/showUserExample")
	public String showUsers(Model model) {
		return "redirect:/1/showUser.do";
	}

	@RequestMapping("/userList")
	public String list(ModelMap model) {
		model.put("users", userService.getUserEntities());
		return "user/list";
	}

	@RequestMapping("/user/{id}/detail")
	public String detail(@PathVariable(value = "id") String id, ModelMap model) {
		model.put("user", userService.getUserEntityById(id));
		return "user/detail";
	}

}